/**
 * 系统名称: 企业财资
 * 模块名称: repair-boot
 * 类 名 称: AutoDispatchSystem.java
 * 软件版权: 恒生电子股份有限公司
 * 修改记录:
 * 修改人员:
 * 修改说明:
 * ============ ============================================
 * zhanghong 创建
 * ============ ============================================
 */
package com.mt.repair.service.repairManagement;

import com.mt.common.core.config.RabbitMqConfig;
import com.mt.common.core.security.RedisUtil;
import com.mt.common.core.web.JsonResult;
import com.mt.common.system.entity.User;
import com.mt.common.system.service.UserService;
import com.mt.repair.entity.repairManagement.RepairOrder;
import com.mt.repair.service.repairManagement.RepairOrderService;
import io.swagger.models.auth.In;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 * @author zhanghong
 * @date 2023-02-25 19:46
 */
@Component
@RabbitListener(queues = {RabbitMqConfig.MSG_QUEUE})
public class AutoDispatchSystem {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private Redisson redisson;
    @Autowired
    private RepairOrderService repairOrderService;

    @RabbitHandler
    public void dispatch(RepairOrder repairOrder){
        List<Long>  roleIdList=new ArrayList<>();
        roleIdList.add(17L);
        List<User> users = userService.getUserIdByRoleId(roleIdList);
        RLock autoDispatchLock = redisson.getLock("autoDispatchLock");
        autoDispatchLock.lock();
        try {
            if(!redisUtil.hasKey("autoDispatchIndex")){
                redisUtil.set("autoDispatchIndex",0);
            }
            long autoDispatchIndex = redisUtil.incr("autoDispatchIndex", 1);
            int currentIndex=(int)autoDispatchIndex-1;
            if(currentIndex>=users.size()){
                redisUtil.set("autoDispatchIndex",0);
                currentIndex=0;
            }
            //获取当前应该派单的维修工
            User user = users.get(currentIndex);
            //订单绑定维修工
            //repairOrder.setRepairApplicantId(user.getEid());
            JsonResult result=repairOrderService.dispatch(user.getEid(),repairOrder.getEid());
            if(result.getCode()==0L){
                repairOrder.setRepairmanId(user.getEid());
                this.repairOrderService.sendWxMessage(repairOrder);
            }
            autoDispatchLock.unlock();
        }catch (Exception e){
            e.printStackTrace();
            autoDispatchLock.unlock();
        }


    }
}
